package com.qf.emqx;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * 使用java客户端向emqx服务器发送消息
 */
public class PublishMessageDemo {

    public static void main(String[] args) throws Exception {

        //1：实例化MqttClient
        int qos = 2;
        String broker = "tcp://47.110.143.177:1883";
        String clientId = "java客户端的名字";
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient client = new MqttClient(broker, clientId, persistence);


        //2： MQTT 连接选项
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName("qf");
        connOpts.setPassword("qf".toCharArray());
        // 保留会话
        connOpts.setCleanSession(true);

        //3： 建立连接
        client.connect(connOpts);


        //4：发送数据
        MqttMessage message = new MqttMessage("hello".getBytes());
        message.setQos(qos);




        client.publish("topic2", message);

    }
}
